import axios from 'axios'
import { ElMessage } from 'element-plus'
import { parseTime } from './parse-time'
import { Log } from '@/utils/interface'
import { useUserStore, useSettingStore } from '@/stores'
const ENV = (import.meta as any).env

function addBug(error: string, info?: string) {
  const userStore = useUserStore()
  const settingStore = useSettingStore()
  const data: Log = {
    url: window.location.href,
    info,
    error,
    // 手动添加的type 为 info
    type: 'Ajax',
    name: userStore.userInfo.username,
    time: parseTime(new Date()),
  }
  settingStore.errorLog.push(data)
}

const service = axios.create({
  baseURL: ENV.VITE_BASE_API,
  timeout: ENV.VITE_TIMEOUT,
})

service.defaults.headers['content-type'] = 'application/json'

service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    // 在发送请求之前做些什么
    if (userStore.vToken) {
      config.headers['Token'] = userStore.vToken
    }

    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  },
)

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    let code
    // if (ENV.VITE_MOCK === 'true') {
    //   code = JSON.parse(response.request.response).code
    // } else {
    // }
    code = response.data.code || response.status
    // console.log(code, response)
    switch (code) {
      case 502:
        ElMessage({ message: response.data.message, type: 'warning' })
        return Promise.reject(response)
      case 401:
        ElMessage({ message: response.data.message, type: 'error' })
        return Promise.reject(response)

      // .then((res) => {
      //     router.push('/login')
      // }).catch((err) => {

      // });
      case 200:
        return response.data
      default:
        ElMessage({ message: response.data.msg, type: 'error' })
        addBug(response.data.message, code)
        return Promise.reject(response.data)
    }
  },
  (error) => {
    if (error.response.data.code === 10001) {
      const userStore = useUserStore()
      ElMessage({ message: error.response.data.msg, type: 'error' })
      userStore.outLogin()
      return Promise.reject(error.response)
    }
    // 获取当前语言
    ElMessage({ message: error.response.data.msg, type: 'error' })
    addBug(error.response.data.message, error.response.status)
    return Promise.reject(error)
  },
)

export default service
